# -*- coding: UTF-8 -*-

# 在Python3.0测试通过
# 需要在gitlab里面新建一个AccessToken填入gitlabToken

import datetime
import sys

import requests

if sys.version_info < (3, 0):
    import urllib
else:
    from urllib.request import urlopen
import json
import os

gitlabAddress = '19.39.39.149'  # git的地址
gitlabToken = 'XXXXXXXX'  # gitlab的token，在gitlab的设置里有生产临时token


class ProjectInfo(json.JSONEncoder):
    """
      工程信息的结构体
    """
    projectId = None
    thisProjectURL = None
    description = None
    nameWithNamespace = None


class MemberDetails(ProjectInfo, json.JSONEncoder):
    """
      项目成员结构体
    """
    userId = None
    userCnName = None
    userName = None
    userLevel = None
    userExpiryDate = None
    userAccessLevel = None


def make_dir_safe(file_path):
    """
      工具方法：写文件时，如果关联的目录不存在，则进行创建
      :param file_path:文件路径或者文件夹路径
      :return:
      """
    if file_path.endswith("/"):
        if not os.path.exists(file_path):
            os.makedirs(file_path)
    else:
        folder_path = file_path[0:file_path.rfind('/') + 1]
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)


def write_to_csv(file_path, proJectMemberList, extra):
    """
      工具方法：将结果写入csv，从#final_commit_map参数解析业务数据
      :param file_path:文件路径
      :param proJectMemberList: 项目成员信息
      :param extra:额外数据列
      :return:
      """
    make_dir_safe(file_path)
    print("开始写文件---------------------------------")
    with open(file_path, 'w') as out:
        title = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (
            "项目id", "项目描述", "项目路径", "项目组空间", "用户id", "用户中文名", "用户账号", "用户权限", "权限有效期", "额外信息")
        out.write(title + "\n")
        for csvCow in proJectMemberList:
            var = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (
                csvCow.projectId, csvCow.description, csvCow.thisProjectURL, csvCow.nameWithNamespace,
                csvCow.userId, csvCow.userCnName, csvCow.userName, csvCow.userLevel, csvCow.userExpiryDate, extra)
            out.write(var + '\n')
        out.close()


def get_member(project_info):
    """
    依据项目id统计所有成员
    """
    members_list = []
    # 成员超过100个需要分页
    for index in range(1, 11):
        members_url = "http://%s/api/v4/projects/%s/members?private_token=%s&per_page=100&page=%d" % (
            gitlabAddress, project_info.projectId, gitlabToken, index)
        if sys.version_info < (3, 0):
            members = urllib.urlopen(members_url)
        else:
            members = urlopen(members_url)
        all_members = json.loads(members.read().decode(encoding='UTF-8'))
        if len(all_members) == 0:
            return members_list

        # print('用户信息: ')
        for m in all_members:
            if m['state'] == 'blocked':
                continue
            user_id = m['id']
            user_cn_name = m['name']
            user_name = m['username']
            user_access_level = m['access_level']
            user_level = ''
            user_expiry_date = m['expires_at']
            if user_expiry_date is None:
                user_expiry_date = '无期限'

            match user_access_level:
                case 10:
                    user_level = 'Guest'
                case 20:
                    user_level = 'Reporter'
                case 30:
                    user_level = 'Developer'
                case 40:
                    user_level = 'Master'
                case 50:
                    user_level = 'Owner'
            details = MemberDetails()
            details.projectId = project_info.projectId
            details.userId = user_id
            details.userCnName = user_cn_name
            details.userName = user_name
            details.userLevel = user_level
            details.userAccessLevel = user_access_level
            details.userExpiryDate = user_expiry_date
            details.thisProjectURL = project_info.thisProjectURL
            details.description = project_info.description
            details.nameWithNamespace = project_info.nameWithNamespace
            members_list.append(details)
        return members_list


def get_all_project():
    """
    获取所有项目的成员信息
    """
    all_project_member_list = []
    for index in range(1, 100):
        # 获取所有项目信息
        url = "http://%s/api/v4/projects?private_token=%s&per_page=100&page=%d" % (gitlabAddress, gitlabToken, index)
        if sys.version_info < (3, 0):
            all_projects = urllib.urlopen(url)
        else:
            all_projects = urlopen(url)
        all_projects_dict = json.loads(all_projects.read().decode(encoding='UTF-8'))
        if len(all_projects_dict) == 0:
            break
        # 遍历每个项目的成员
        for thisProject in all_projects_dict:
            description = thisProject['description']
            if description is not None:
                description = description.replace("\r\n", "。")
            # 项目信息
            projectInfo = ProjectInfo()
            projectInfo.projectId = thisProject['id']
            projectInfo.thisProjectURL = thisProject['http_url_to_repo']
            projectInfo.nameWithNamespace = thisProject['name_with_namespace']
            projectInfo.description = description
            # 一个项目的所有成员信息
            one_project_members_list = get_member(projectInfo)
            all_project_member_list.extend(one_project_members_list)
    # 所有项目遍历完成，返回项目信息
    return all_project_member_list


def update_member(member_info):
    """
    更新非master项目成员的有效期
    """
    headers = {'content-type': 'application/json'}
    print('项目id：' + str(member_info.projectId) + '用户名：' + member_info.userCnName)
    if member_info.userAccessLevel != 40:
        # 更新项目成员信息
        urlMember = 'http://%s/api/v4/projects/%s/members/%s?private_token=%s' % (
            gitlabAddress, id, member_info.userId, gitlabToken)
        data = {'access_level': member_info.userAccessLevel, 'expires_at': "2022-12-31"}
        get_feedback_isue = requests.put(urlMember, json=data, headers=headers)
        print(get_feedback_isue.__dict__)


if __name__ == "__main__":
    start_time = datetime.datetime.now()
    print(start_time)
    # projectInfo = ProjectInfo()
    # # 项目id
    # projectInfo.projectId = 1225
    # # 项目链接
    # projectInfo.thisProjectURL = "http://10.39.39.18/DataHub/encdate-developer-doc.git"
    # # 项目位置
    # projectInfo.nameWithNamespace = "数据枢纽 / encdate-developer-doc"
    # # 项目描述
    # projectInfo.description = "小组开发文档共享"
    # # 一个项目的所有成员信息
    # one_project_members_list = get_member( projectInfo)
    # # 导出为csv
    # write_to_csv("./dist/project_%s.csv" % gitlabAddress, one_project_members_list, "")

    # 获取所有项目成员信息
    project_members_list = get_all_project()
    # 导出为csv
    write_to_csv("./dist/project_%s.csv" % gitlabAddress, project_members_list, "")
    end_time = datetime.datetime.now()
    print("耗时（秒）:" + str((end_time - start_time).seconds))
